package chat;

import java.io.*;
import java.util.*;

public class PeerWriter extends Thread
{
    private List zLines = new ArrayList();
    private BufferedWriter zWriter;

    public PeerWriter( OutputStream pOs )
    {
        IllegalArgument.ifNull( "Os" , pOs );
        zWriter = new BufferedWriter( new OutputStreamWriter( pOs ) );
        start();
    }

    public synchronized void writeLine( String pMessage )
    {
        IllegalArgument.ifNull( "Message" , pMessage );
        zLines.add( pMessage );
        notifyAll();
    }

    private synchronized String getline()
    {
        while ( zLines.isEmpty() )
        {
            try
            {
                wait();
            }
            catch ( InterruptedException e )
            {
            }
        }

        Object message = zLines.get( 0 );
        zLines.remove( 0 );
        return (String) message;
    }

    public void run()
    {
        try
        {
            while ( true )
            {
                zWriter.write( getline() );
                zWriter.newLine();
                zWriter.flush();
            }
        }
        catch ( IOException e )
        {
            e.printStackTrace();
            System.exit( 1 );
        }
    }
}
